package com.dzl.fulu.sup.open.api.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Map;
import java.util.Set;

public class JSONUtil {
  private static Gson gson = new Gson();

  /**
   * 将 JSON 字符串转为 Java 对象
   */
  public static <T> T fromJSON(String json, Class<T> type) {
    T obj;
    try {
      obj = gson.fromJson(json, type);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return obj;
  }

  /**
   * json字符串转list或者map
   */
  public static <T> T fromJSON(String json, TypeToken<T> typeToken) {
    return gson.fromJson(json, typeToken.getType());
  }

  /**
   * 将 Java 对象转为 JSON 字符串
   */
  public static <T> String toJSON(T obj) {
    String jsonStr;
    try {
      jsonStr = gson.toJson(obj);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return jsonStr;
  }

  /**
   *
   * 对json数据key进行替换
   * @author
   * @date 2019-11-08
   *
   */
  public static JSONObject changeJsonObj(JSONObject jsonObj, Map<String, String> keyMap) {
    JSONObject resJson = new JSONObject();
    Set<String> keySet = jsonObj.keySet();
    for (String key : keySet) {
      String resKey = keyMap.get(key) == null ? key : keyMap.get(key);
      try {
        JSONObject jsonobj1 = jsonObj.getJSONObject(key);
        resJson.put(resKey, changeJsonObj(jsonobj1, keyMap));
      } catch (Exception e) {
        try {
          JSONArray jsonArr = jsonObj.getJSONArray(key);
          resJson.put(resKey, changeJsonArr(jsonArr, keyMap));
        } catch (Exception x) {
          resJson.put(resKey, jsonObj.get(key));
        }
      }
    }
    return resJson;
  }
  public static JSONArray changeJsonArr(JSONArray jsonArr,Map<String, String> keyMap) {
    JSONArray resJson = new JSONArray();
    for (int i = 0; i < jsonArr.size(); i++) {
      JSONObject jsonObj = jsonArr.getJSONObject(i);
      resJson.add(changeJsonObj(jsonObj, keyMap));
    }
    return resJson;
  }
}
